package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.net.www.http.HttpClient;

import java.io.IOException;
import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;


    @Autowired
    private UserMapper userMapper;
    /**
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) throws IOException {
//        调用微信接口服务,获得openid

        CloseableHttpClient aDefault = HttpClients.createDefault();
        String Appid = weChatProperties.getAppid();
        String secret = weChatProperties.getSecret();
        String code = userLoginDTO.getCode();
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + Appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse reponse = aDefault.execute(httpGet);
        HttpEntity entity = reponse.getEntity();
        String body = EntityUtils.toString(entity);
        JSONObject jsonObject = JSON.parseObject(body);
        String openid = jsonObject.getString("openid");


//        {"session_key":"vuv++t91Jv\/R8xx2kHyNIQ==","openid":"o2CnP5Rthxj9hAVkb5jRhmseH2fs"}


//        判断openid是否为空
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        User user=null;
//        判断是否为新用户.根据openid.
         user = userMapper.getByOpenid(openid);

        if (user == null) {
//         //        新的用户自动完成注册.   新用戶
           user = User.builder().openid(openid).createTime(LocalDateTime.now()).build();
            userMapper.saveUser(user);
        }

//        返回对象.

        return user;
    }
}
